<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/9
 * Time: 18:33
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterAuthRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

class RegisterController extends Controller
{
    public $loginAfterSignUp = true;
    /*
     * 生成token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        $user = new User();
        $user->user_number = $request->user_number;
        $user->user_type   = $request->user_type;
        $user->password    = bcrypt($request->password);
        $user->save();

        if ($this->loginAfterSignUp) {
            return $this->login($request);
        }

        return response()->json([
            'success' => true,
            'data' => $user
        ], 200);

    }

    public function login(Request $request)
    {
        $input = $request->only('user_number', 'password');
        $jwt_token = null;
        $userObj = User::where(['user_number'=>$input['user_number']])->first();

        if (!$jwt_token = auth('api')->login($userObj)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid Email or Password',
            ], 401);
        }
        return response()->json([
            'success' => true,
            'token' => $jwt_token,
        ]);
    }

    /*
     * 退出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function logout(Request $request)
    {
        auth('api')->logout();
        return response()->json([
            'code'=>0,
            'success' => '退出成功',
        ]);
    }

    /*
     * 获取用户的信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function getAuthUser(Request $request)
    {

        $user = auth('api')->user()->toArray();
        echo "<pre>";
        print_r($user);
        echo "</pre>";
        exit();


        return response()->json(['user' => $user]);
    }
}
